﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DemoData.Model;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Hallenberg.Core;

namespace DemoData.Providers
{
    public class BaseProvider<T> : IProvider<T>
        where T : ModelBase
    {
        private Dictionary<int, T> m_Model = new Dictionary<int, T>();

        public IQueryable<T> Get()
        {
            return m_Model.Values.AsQueryable();
        }

        public void Save(T value)
        {
            Debug.Assert(value != null);
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            ValidationResults validationResults = Validation.Validate<T>(value);

            if (validationResults.Count > 0)
            {
                ValidationException validationException = new ValidationException();

                foreach (ValidationResult validationResult in validationResults)
                {
                    validationException.AddValidationError(validationResult.Key, validationResult.Message);
                }

                throw validationException;
            }

            if (value.Id == 0)
            {
                value.Id = m_Model.Count + 1;
            }

            m_Model[value.Id] = value;
        }

        public void Delete(T value)
        {
            Debug.Assert(value != null);
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (!m_Model.ContainsKey(value.Id))
            {
                throw new InvalidOperationException("Value does not exist in repository");
            }

            m_Model.Remove(value.Id);
        }

        public void Clear()
        {
            m_Model.Clear();
        }
    }
}
